<template>
  <div class="goods-container">
    <el-card>
      <!-- 商品列表 -->
      <template v-if="!isPlusGoods">
        <!-- 头部 -->
        <el-header>
          <div class="left">
            <strong>搜索商品：</strong>
            <el-input
              clearable
              size="small"
              v-model.trim.lazy="params.query"
              class="input"
              placeholder="请输入商品名称后敲回车"
              @keyup.enter.native="getGoodsList(params)"
            ></el-input>
          </div>
          <el-button
            class="plus-btn"
            size="mini"
            :style="btnStyle"
            icon="el-icon-plus"
            @click="showAddGoodsCard"
          >
            添加商品
          </el-button>
        </el-header>
        <!-- 表格 -->
        <el-table
          :data="goodsList"
          style="width: 100%"
          border
          stripe
          :style="fontStyle"
        >
          <el-table-column align="center" type="index" label="#">
          </el-table-column>
          <el-table-column align="center" prop="goods_name" label="商品名称">
          </el-table-column>
          <el-table-column
            align="center"
            prop="goods_price"
            label="商品价格"
            width="80"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="goods_weight"
            label="商品重量"
            width="80"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="goods_number"
            label="商品库存"
            width="80"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="time"
            label="创建时间"
            width="160"
          >
          </el-table-column>
          <el-table-column align="center" label="操作" width="200">
            <template slot-scope="{ row }">
              <el-button
                size="mini"
                :style="btnStyle"
                icon="el-icon-edit"
                @click="$message.info('该接口暂未开放')"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                :style="btnStyle"
                icon="el-icon-delete"
                @click="deleteGoodsHandler(row.goods_id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <my-pagination
          :total="goodsListData.total"
          :params="params"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        ></my-pagination>
      </template>
      <!-- 添加商品 -->
      <template v-else>
        <el-alert
          title="添加商品"
          description="点击右边×可以关闭"
          type="info"
          center
          show-icon
          style="width: 90%; margin: 0 auto"
          @close="isPlusGoods = false"
        >
        </el-alert>
        <!-- 步骤条 -->
        <el-steps
          :active="activeTabIndex * 1"
          style="margin-top: 15px"
          finish-status="success"
          align-center
        >
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
        </el-steps>
        <!-- 表单 -->
        <el-form
          ref="addGoodsFormRef"
          :rules="addGoodsRules"
          :model="addGoodsForm"
          label-width="80px"
        >
          <!-- tabs -->
          <el-tabs
            v-model="activeTabIndex"
            tab-position="left"
            style="height: 300px; margin-top: 15px"
            :before-leave="tabBeforeLeaveHandler"
            class="tab-container"
          >
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addGoodsForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input
                  type="number"
                  v-model="addGoodsForm.goods_price"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input
                  type="number"
                  v-model="addGoodsForm.goods_number"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input
                  type="number"
                  v-model="addGoodsForm.goods_weight"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品分类">
                <el-cascader
                  v-model="goodsCate"
                  :options="goodsCateList"
                  :props="goodsCateProps"
                  @change="selectGoodsCate"
                ></el-cascader>
              </el-form-item>
            </el-tab-pane>
            <!-- 商品动态参数 -->
            <el-tab-pane label="商品参数" name="1">
              <el-form-item v-for="many in manyParamsList" :key="many.attr_id">
                <el-checkbox-group v-model="many.attr_vals">
                  <el-checkbox
                    v-for="(m, i) in many.attr_vals"
                    :key="i"
                    :label="m"
                    border
                  ></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>
            <!-- 商品静态参数 -->
            <el-tab-pane label="商品属性" name="2">
              <el-form-item
                :label="only.attr_name"
                v-for="only in onlyParamsList"
                :key="only.attr_id"
              >
                <el-input v-model="only.attr_vals"></el-input>
              </el-form-item>
            </el-tab-pane>
            <!-- 商品图片上传 -->
            <el-tab-pane label="商品图片" name="3">
              <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handlerSuccess"
                :headers="reqHeaders"
                list-type="picture"
              >
                <el-button size="small" :style="btnStyle">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-tab-pane>
            <!-- 商品介绍 -->
            <el-tab-pane label="商品内容" name="4">
              <!-- 编辑器 -->
              <quill-editor
                v-model="addGoodsForm.goods_introduce"
              ></quill-editor>
              <el-button
                :style="btnStyle"
                style="margin-top: 20px; float: right"
                @click="addGoodsConfirmHandler"
              >
                添加
              </el-button>
            </el-tab-pane>
          </el-tabs>
        </el-form>
        <!-- 图片预览对话框 -->
        <el-dialog
          title=""
          :visible.sync="imgPreviewDialogVisible"
          width="50%"
          :before-close="imgPreviewDialogBeforeClose"
        >
          <img class="preview-img" :src="previewImgSrc" alt="" />
        </el-dialog>
      </template>
    </el-card>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex'
import { getStorage } from '../../utils/auth'
export default {
  name: 'goods',
  data() {
    return {
      // 查询参数
      params: {
        query: '',
        pagenum: 1,
        pagesize: 5,
      },
      isPlusGoods: false, // 添加商品card的状态
      activeTabIndex: 0, // 激活的tab索引
      // 添加商品表单对象
      addGoodsForm: {
        goods_name: '',
        goods_cat: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        goods_introduce: '',
        pics: [], // 商品图片
        attrs: [], // 商品参数
      },
      // 添加商品表单验证对象
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请填写商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请填写商品价格', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请填写商品数量', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请填写商品重量', trigger: 'blur' },
        ],
      },
      goodsCate: [], // 保存选中的商品分类数组
      //  商品分类级联选择器配置
      goodsCateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
      },
      // 上传图片的url
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传图片请求头
      reqHeaders: { Authorization: getStorage('userInfo').token },
      imgPreviewDialogVisible: false, // 图片预览对话框状态
      previewImgSrc: '', // 预览图地址
    }
  },
  computed: {
    ...mapState('goods', ['goodsListData', 'goodsCateList']),
    ...mapState('params', ['manyParamsList', 'onlyParamsList']),
    ...mapGetters('goods', ['goodsList']),
  },
  methods: {
    ...mapActions('goods', [
      'getGoodsList',
      'addGoods',
      'deleteGoods',
      'getGoodsCateList',
    ]),
    ...mapActions('params', ['getCateParams']),
    handleSizeChange(pagesize) {
      this.params.pagesize = pagesize
      this.getGoodsList(this.params)
    },
    handleCurrentChange(pagenum) {
      this.params.pagenum = pagenum
      this.getGoodsList(this.params)
    },
    // 删除商品的回调
    async deleteGoodsHandler(id) {
      try {
        await this.$messageBox.confirm('确定删除该商品吗？', '提示')
        try {
          await this.deleteGoods(id)
          this.getGoodsList(this.params)
          this.$message.success('删除成功')
        } catch (error) {
          this.$message.error(error)
        }
      } catch (error) {
        this.$message.info('已取消删除')
      }
    },
    // 显示添加商品卡片的回调
    showAddGoodsCard() {
      this.isPlusGoods = true
      // 获取商品分类
      this.getGoodsCateList()

      this.clearGoodsParams()
    },
    // 清空残留数据
    clearGoodsParams() {
      this.addGoodsForm = {
        goods_name: '',
        goods_cat: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        goods_introduce: '',
        pics: [],
        attrs: [],
      }
      this.goodsCate = []
      this.activeTabIndex = 0
    },
    // 选择商品分类回调
    selectGoodsCate(value) {
      this.addGoodsForm.goods_cat = value.join(',')
    },
    // tab切换前的回调
    tabBeforeLeaveHandler(activeName, oldActiveName) {
      // 如果未选中商品分类，不切换tab
      if (activeName !== '0' && !this.goodsCate.length) {
        this.$message.info('请先选择商品分类')
        return false
      }
      const id = this.goodsCate[this.goodsCate.length - 1]
      // 获取动态参数
      if (activeName === '1') {
        this.getCateParams({
          id,
          sel: 'many',
        })
      } else if (activeName === '2') {
        // 获取静态参数
        this.getCateParams({
          id,
          sel: 'only',
        })
      }
    },
    // 点击确定添加商品按钮回调
    addGoodsConfirmHandler() {
      this.$refs.addGoodsFormRef.validate(async v => {
        if (!v) return this.$message.info('请完整填写商品信息')
        this.manyParamsList.forEach(many => {
          const obj = {
            attr_id: many.attr_id,
            attr_value: many.attr_vals.join(','),
          }
          this.addGoodsForm.attrs.push(obj)
        })
        this.onlyParamsList.forEach(only => {
          const obj = {
            attr_id: only.attr_id,
            attr_value: only.attr_vals,
          }
          this.addGoodsForm.attrs.push(obj)
        })
        try {
          await this.addGoods(this.addGoodsForm)
          this.$message.success('添加商品成功')
          this.isPlusGoods = false
          this.getGoodsList(this.params)
        } catch (error) {
          console.log(error)
        }
      })
    },
    // 点击文件列表中已上传的文件的回调
    handlePreview(file) {
      this.previewImgSrc = file.response.data.url
      this.imgPreviewDialogVisible = true
    },
    //删除图片的回调
    handleRemove(file) {
      const path = file.response.data.tmp_path
      const index = this.addGoodsForm.pics.findIndex(item => item.pic === path)
      this.addGoodsForm.pics.splice(index, 1)
    },
    // 图片上传成功的回调
    handlerSuccess(res, file, fileList) {
      // 将图片对象添加到商品参数的数组中
      const picObj = { pic: res.data.tmp_path }
      this.addGoodsForm.pics.push(picObj)
    },
    // 图片预览关闭的回调
    imgPreviewDialogBeforeClose(done) {
      done()
      this.imgPreviewDialogVisible = false
      this.previewImgSrc = ''
    },
  },
  mounted() {
    this.getGoodsList(this.params)
    this.$on('handleSizeChange', this.handleSizeChange)
    this.$on('handleCurrentChange', this.handleCurrentChange)
  },
}
</script>

<style lang="scss" scoped>
.goods-container {
  .el-header {
    line-height: 40px;
    .left {
      float: left;
    }
    strong {
      font-size: 14px;
    }
    .input {
      margin-left: 8px;
      width: 260px !important;
    }
    .plus-btn {
      margin-left: 50px;
    }
  }
  .tab-container {
    width: 90%;
    margin: 15px auto;
    height: auto !important;
    min-height: 300px !important;
  }
  .preview-img {
    width: 100%;
    height: 100%;
  }
}
</style>
